{
    "cells": [
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "# Python流程控制\n",
                "\n",
                "在本课中，我们将学习Python的流程控制结构，包括条件语句和循环结构，这些是构建复杂程序的基础。"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## 1. 条件语句\n",
                "\n",
                "条件语句允许程序根据不同的条件执行不同的代码块，是程序决策的基础。"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 1.1 if语句\n",
                "\n",
                "最基本的条件语句是`if`语句，当条件为真时执行代码块："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 基本if语句\n",
                "age = 20\n",
                "\n",
                "if age >= 18:\n",
                "    print(\"您已成年，可以进入网站。\")\n",
                "\n",
                "print(\"程序继续执行...\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**if语句的应用场景:**\n",
                "1. 用户验证 - 检查登录信息是否正确\n",
                "2. 数据验证 - 确保输入数据符合要求\n",
                "3. 功能控制 - 控制程序的不同路径\n",
                "4. 错误处理 - 检测可能的错误情况"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：简单的登录验证\n",
                "username = input(\"请输入用户名：\")\n",
                "password = input(\"请输入密码：\")\n",
                "\n",
                "correct_username = \"admin\"\n",
                "correct_password = \"123456\"\n",
                "\n",
                "if username == correct_username and password == correct_password:\n",
                "    print(\"登录成功！欢迎回来，管理员。\")\n",
                "    print(\"您可以访问所有功能。\")\n",
                "\n",
                "print(\"程序继续处理其他逻辑...\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 1.2 if-else语句\n",
                "\n",
                "`if-else`语句允许程序在条件为真时执行一个代码块，在条件为假时执行另一个代码块："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# if-else语句\n",
                "age = 16\n",
                "\n",
                "if age >= 18:\n",
                "    print(\"您已成年，可以进入网站。\")\n",
                "else:\n",
                "    print(\"您未成年，不能进入网站。\")\n",
                "\n",
                "print(\"程序继续执行...\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**if-else语句的应用场景:**\n",
                "1. 双向选择 - 根据条件执行两种不同的操作\n",
                "2. 错误处理 - 提供正常路径和异常路径\n",
                "3. 用户界面 - 根据用户输入提供不同响应\n",
                "4. 游戏逻辑 - 玩家角色根据状态执行不同动作"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：奇偶数判断器\n",
                "try:\n",
                "    number = int(input(\"请输入一个整数：\"))\n",
                "\n",
                "    if number % 2 == 0:  # 使用取余运算符，如果余数为0则是偶数\n",
                "        print(f\"{number}是偶数\")\n",
                "    else:\n",
                "        print(f\"{number}是奇数\")\n",
                "except ValueError:\n",
                "    print(\"输入无效，请输入一个整数。\")\n",
                "\n",
                "print(\"1111\")    "
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "![条件语句](https://www.runoob.com/wp-content/uploads/2013/11/if-condition.jpg)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 1.3 if-elif-else语句\n",
                "\n",
                "`if-elif-else`语句允许程序检查多个条件，并根据第一个为真的条件执行相应的代码块："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# if-elif-else语句\n",
                "score = 85\n",
                "\n",
                "# if score >= 90:\n",
                "#     grade = \"A\"\n",
                "# elif score >= 80:\n",
                "#     grade = \"B\"\n",
                "# elif score >= 70:\n",
                "#     grade = \"C\"\n",
                "# elif score >= 60:\n",
                "#     grade = \"D\"\n",
                "# else:\n",
                "#     grade = \"F\"\n",
                "\n",
                "# print(f\"您的分数是{score}，对应的等级是{grade}\")\n",
                "\n",
                "if( score < 90 and score >= 80):\n",
                "    print(\"b\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**if-elif-else语句的应用场景:**\n",
                "1. 多条件分类 - 将数据分类到多个类别\n",
                "2. 菜单系统 - 根据用户选择执行不同功能\n",
                "3. 状态机 - 根据当前状态决定下一步操作\n",
                "4. 评分系统 - 根据不同分数范围给出评级"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：简易计算器\n",
                "try:\n",
                "    num1 = float(input(\"请输入第一个数字：\"))\n",
                "    num2 = float(input(\"请输入第二个数字：\"))\n",
                "    operation = input(\"请选择运算（+、-、*、/）：\")\n",
                "\n",
                "    if operation == \"+\":\n",
                "        result = num1 + num2\n",
                "        print(f\"{num1} + {num2} = {result}\")\n",
                "    elif operation == \"-\":\n",
                "        result = num1 - num2\n",
                "        print(f\"{num1} - {num2} = {result}\")\n",
                "    elif operation == \"*\":\n",
                "        result = num1 * num2\n",
                "        print(f\"{num1} * {num2} = {result}\")\n",
                "    elif operation == \"/\":\n",
                "        if num2 == 0:\n",
                "            print(\"错误：除数不能为零！\")\n",
                "        else:\n",
                "            result = num1 / num2\n",
                "            print(f\"{num1} / {num2} = {result}\")\n",
                "    else:\n",
                "        print(\"不支持的运算符，请使用+、-、*或/\")\n",
                "except ValueError:\n",
                "    print(\"输入无效，请确保输入的是数字。\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 1.4 嵌套条件语句\n",
                "\n",
                "条件语句可以嵌套使用，即在一个条件语句内部包含另一个条件语句："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 嵌套条件语句\n",
                "age = 25\n",
                "has_id = True\n",
                "\n",
                "if age >= 18:\n",
                "    print(\"年龄符合要求\")\n",
                "    if has_id:\n",
                "        print(\"身份证明已验证，允许购买。\")\n",
                "    else:\n",
                "        print(\"请出示有效身份证明。\")\n",
                "else:\n",
                "    print(\"未成年人不得购买此商品。\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**嵌套条件语句的应用场景:**\n",
                "1. 复杂决策 - 需要检查多个相关条件的情况\n",
                "2. 权限控制 - 多层级的权限验证\n",
                "3. 表单验证 - 逐步验证不同字段\n",
                "4. 游戏规则 - 实现复杂的游戏规则判断"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：电影票价计算\n",
                "age = int(input(\"请输入您的年龄：\"))\n",
                "day = input(\"今天是星期几？(1-7)：\")\n",
                "student = input(\"您是学生吗？(y/n)：\")\n",
                "\n",
                "base_price = 40  # 基本票价\n",
                "\n",
                "if age < 12:\n",
                "    price = base_price * 0.5  # 儿童半价\n",
                "    print(f\"儿童票：{price}元\")\n",
                "elif age >= 60:\n",
                "    price = base_price * 0.6  # 老人6折\n",
                "    print(f\"老人票：{price}元\")\n",
                "else:\n",
                "    if student.lower() == 'y':\n",
                "        price = base_price * 0.8  # 学生8折\n",
                "        print(f\"学生票：{price}元\")\n",
                "    else:\n",
                "        if day == '3':\n",
                "            price = base_price * 0.9  # 周三9折\n",
                "            print(f\"周三特惠票：{price}元\")\n",
                "        else:\n",
                "            price = base_price  # 正常价格\n",
                "            print(f\"普通票：{price}元\")\n",
                "\n",
                "print(\"祝您观影愉快！\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 1.5 条件表达式（三元运算符）\n",
                "\n",
                "Python提供了一种简洁的条件表达式，有时被称为“三元运算符”："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 条件表达式\n",
                "age = 20\n",
                "status = \"成年\" if age >= 18 else \"未成年\"\n",
                "\n",
                "print(status)\n",
                "if(age>=18):\n",
                "    status=\"成年\"\n",
                "else:\n",
                "    status=\"未成年\"\n",
                "print(status)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**条件表达式的应用场景:**\n",
                "1. 简单赋值 - 根据条件赋予不同的值\n",
                "2. 格式化字符串 - 选择不同的文本\n",
                "3. 返回值 - 函数根据条件返回不同值\n",
                "4. UI显示 - 根据状态显示不同内容"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：简化表达式\n",
                "temperature = float(input(\"请输入当前温度（摄氏度）：\"))\n",
                "\n",
                "# 使用条件表达式简化代码\n",
                "weather = \"热\" if temperature > 30 else \"温暖\" if temperature > 20 else \"凉爽\" if temperature > 10 else \"冷\"\n",
                "\n",
                "print(f\"当前温度{temperature}°C，天气{weather}。\")\n",
                "\n",
                "# 穿衣建议\n",
                "suggestion = \"穿短袖\" if temperature > 25 else \"穿长袖\" if temperature > 15 else \"穿外套\" if temperature > 5 else \"穿羽绒服\"\n",
                "print(f\"穿衣建议：{suggestion}\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## 2. 循环结构\n",
                "\n",
                "循环结构允许程序重复执行代码块，是处理大量数据或重复任务的基础。"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "![for](https://www.runoob.com/wp-content/uploads/2013/11/A71EC47E-BC53-4923-8F88-B027937EE2FF.jpg)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 2.1 for循环\n",
                "\n",
                "`for`循环用于遍历序列（如列表、元组、字符串等）中的元素："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 基本for循环\n",
                "fruits = [\"苹果\", \"香蕉\", \"橙子\", 2]\n",
                "\n",
                "for item in fruits:\n",
                "    print(item)\n",
                "\n",
                "\n",
                "print(\"循环结束\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**for循环的应用场景:**\n",
                "1. 数据处理 - 处理列表或数组中的每个元素\n",
                "2. 文件操作 - 读取文件中的每一行\n",
                "3. 字符串处理 - 处理字符串中的每个字符\n",
                "4. 批量操作 - 对多个对象执行相同操作"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：学生成绩统计\n",
                "students = [\"张三\", \"李四\", \"王五\", \"赵六\", \"钱七\"]\n",
                "scores = [85, 92, 78, 95, 88]\n",
                "\n",
                "# print(students[0])\n",
                "\n",
                "total_score = 0\n",
                "\n",
                "ii=0\n",
                "for score in scores:\n",
                "    total_score += score\n",
                "    print(f\"=={students[ii]}：{scores[ii]}分\")\n",
                "    ii+=1\n",
                "\n",
                "\n",
                "average = total_score / len(scores)\n",
                "print(f\"班级平均分：{average:.2f}\")\n",
                "\n",
                "# 输出每个学生的成绩\n",
                "print(\"\\n学生成绩单：\")\n",
                "for i in range(len(students)):\n",
                "    print(f\"{students[i]}：{scores[i]}分\")\n",
                "\n",
                "# 找出成绩最高的学生\n",
                "highest_score = max(scores)\n",
                "highest_index = scores.index(highest_score)\n",
                "print(f\"\\n最高分：{students[highest_index]}，{highest_score}分\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 2.2 range()函数\n",
                "\n",
                "`range()`函数可以生成一个数字序列，常用于控制循环的次数："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# range()函数示例\n",
                "# 从0开始，到5结束（不包括5）\n",
                "for i in range(5):\n",
                "    print(i)\n",
                "\n",
                "print(\"\\n指定起始值：\")\n",
                "# 从2开始，到8结束（不包括8）\n",
                "for i in range(2, 11):\n",
                "    print(i)\n",
                "\n",
                "print(\"\\n指定步长：\")\n",
                "# 从1开始，到10结束（不包括10），步长为2\n",
                "for i in range(1, 10, 2):\n",
                "    print(i)"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**range()函数的应用场景:**\n",
                "1. 指定次数循环 - 重复执行固定次数的操作\n",
                "2. 索引遍历 - 通过索引访问序列中的元素\n",
                "3. 数值计算 - 生成特定范围的数字\n",
                "4. 表格生成 - 创建带有行号的表格"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：九九乘法表\n",
                "print(\"九九乘法表：\")\n",
                "\n",
                "for i in range(1, 10):  # 第一个因数从1到9\n",
                "    for j in range(1, i + 1):  # 第二个因数从1到i\n",
                "        product = i * j\n",
                "        print(f\"{j} × {i} = {product}\", end=\"\\t\")  # 使用\\t制表符来对齐\n",
                "    print()  # 换行"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 2.3 while循环\n",
                "\n",
                "`while`循环会一直执行代码块，直到条件变为假："
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "![while](https://www.runoob.com/wp-content/uploads/2013/11/886A6E10-58F1-4A9B-8640-02DBEFF0EF9A.jpg)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 基本while循环\n",
                "count = 0\n",
                "\n",
                "while count < 5:\n",
                "    print(f\"当前计数：{count}\")\n",
                "    count += 1\n",
                "\n",
                "print(\"循环结束\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**while循环的应用场景:**\n",
                "1. 未知次数循环 - 循环直到满足特定条件\n",
                "2. 用户输入验证 - 循环直到用户输入有效数据\n",
                "3. 游戏循环 - 游戏主循环，直到游戏结束\n",
                "4. 数据处理 - 处理数据直到达到终止条件"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：猜数字游戏\n",
                "import random\n",
                "\n",
                "# 生成1到100之间的随机数\n",
                "secret_number = random.randint(1, 100)\n",
                "guess_count = 0\n",
                "max_guesses = 10\n",
                "\n",
                "print(\"欢迎参加猜数字游戏！\")\n",
                "print(f\"我已经想好了一个1到100之间的数字，你有{max_guesses}次机会猜测。\")\n",
                "\n",
                "while guess_count < max_guesses:\n",
                "    try:\n",
                "        # 获取用户的猜测\n",
                "        guess = int(input(f\"\\n请输入你的猜测（第{guess_count + 1}次）：\"))\n",
                "        guess_count += 1\n",
                "\n",
                "        # 检查猜测\n",
                "        if guess < secret_number:\n",
                "            print(\"太小了，再大一点！\")\n",
                "        elif guess > secret_number:\n",
                "            print(\"太大了，再小一点！\")\n",
                "        else:\n",
                "            print(f\"恭喜你，猜对了！答案是{secret_number}。\")\n",
                "            print(f\"你用了{guess_count}次猜对。\")\n",
                "            break  # 猜对了，跳出循环\n",
                "\n",
                "        # 显示剩余次数\n",
                "        remaining = max_guesses - guess_count\n",
                "        if remaining > 0:\n",
                "            print(f\"你还有{remaining}次机会。\")\n",
                "\n",
                "    except ValueError:\n",
                "        print(\"请输入有效的数字！\")\n",
                "\n",
                "else:  # 当while循环自然结束（没有通过break跳出）时执行\n",
                "    print(f\"\\n游戏结束，你没有猜对。正确答案是{secret_number}。\")\n",
                "\n",
                "print(\"感谢参与游戏！\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 2.4 循环控制语句\n",
                "\n",
                "Python提供了几个用于控制循环执行的语句："
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "#### break语句\n",
                "\n",
                "`break`语句用于立即退出循环："
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "![break](https://www.runoob.com/wp-content/uploads/2014/09/E5A591EF-6515-4BCB-AEAA-A97ABEFC5D7D.jpg)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# break语句示例\n",
                "for i in range(1, 11):\n",
                "    if i == 5:\n",
                "        print(\"遇到5，退出循环\")\n",
                "        break\n",
                "    print(i)\n",
                "\n",
                "print(\"循环结束\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**break语句的应用场景:**\n",
                "1. 提前退出 - 满足特定条件时结束循环\n",
                "2. 搜索操作 - 找到目标后停止搜索\n",
                "3. 用户交互 - 用户选择退出时结束循环\n",
                "4. 异常情况 - 遇到错误时停止处理"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：查找列表中的元素\n",
                "names = [\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Eve\", \"Frank\"]\n",
                "search_name = input(\"请输入要查找的名字：\")\n",
                "\n",
                "found = False\n",
                "for i, name in enumerate(names):\n",
                "    if name.lower() == search_name.lower():  # 不区分大小写比较\n",
                "        print(f\"找到了！{search_name}在列表中的位置是{i}。\")\n",
                "        found = True\n",
                "        break  # 找到后立即退出循环\n",
                "\n",
                "if not found:\n",
                "    print(f\"没有找到{search_name}。\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "#### continue语句\n",
                "\n",
                "`continue`语句用于跳过当前循环的剩余部分，直接进入下一次循环："
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "![continue](https://www.runoob.com/wp-content/uploads/2014/09/8962A4F1-B78C-4877-B328-903366EA1470.jpg)"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# continue语句示例\n",
                "for i in range(1, 11):\n",
                "    if i % 2 == 0:  # 如果是偶数\n",
                "        continue  # 跳过当前循环的剩余部分\n",
                "    print(i)  # 只打印奇数\n",
                "\n",
                "print(\"循环结束\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**continue语句的应用场景:**\n",
                "1. 跳过特定项 - 不处理满足特定条件的项\n",
                "2. 数据过滤 - 过滤掉不符合条件的数据\n",
                "3. 异常处理 - 跳过出错的项继续处理其他项\n",
                "4. 特殊情况处理 - 对特殊情况简单跳过"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：处理成绩数据（跳过无效数据）\n",
                "scores_data = [85, 92, -1, 78, 100, 999, 65, 70, -5, 91]\n",
                "valid_scores = []\n",
                "\n",
                "print(\"处理成绩数据...\")\n",
                "for score in scores_data:\n",
                "    # 检查成绩是否在有效范围内（0-100）\n",
                "    if score < 0 or score > 100:\n",
                "        print(f\"发现无效成绩：{score}，已跳过\")\n",
                "        continue  # 跳过无效成绩\n",
                "\n",
                "    # 处理有效成绩\n",
                "    valid_scores.append(score)\n",
                "    print(f\"处理成绩：{score}\")\n",
                "\n",
                "# 计算平均分\n",
                "if valid_scores:  # 检查是否有有效成绩\n",
                "    average = sum(valid_scores) / len(valid_scores)\n",
                "    print(f\"\\n有效成绩的平均分：{average:.2f}\")\n",
                "    print(f\"有效成绩数量：{len(valid_scores)}\")\n",
                "else:\n",
                "    print(\"\\n没有有效成绩\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "#### else子句\n",
                "\n",
                "循环可以有一个`else`子句，当循环正常完成（不是通过`break`语句退出）时执行："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 循环的else子句示例\n",
                "for i in range(1, 6):\n",
                "    print(i)\n",
                "else:\n",
                "    print(\"循环正常完成\")\n",
                "\n",
                "print(\"\\n使用break的情况：\")\n",
                "yy=0\n",
                "for i in range(1, 6):\n",
                "    print(i)\n",
                "    if i == 3:\n",
                "        print(\"循环被break中断\")\n",
                "        break\n",
                "    yy+=1\n",
                "else:  # 由于循环被break中断，else子句不会执行\n",
                "    print(\"循环正常完成\")\n",
                "\n",
                "if(yy==5):\n",
                "    print(\"循环正常完成\")\n",
                "else:\n",
                "    print(\"循环被break中断\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**else子句的应用场景:**\n",
                "1. 循环完成检测 - 确认循环正常完成\n",
                "2. 搜索确认 - 确认搜索完整完成但未找到目标\n",
                "3. 验证操作 - 确认所有验证步骤都已执行\n",
                "4. 处理收尾 - 在循环完成后执行清理操作"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：密码验证\n",
                "attempts = 3  # 允许的尝试次数\n",
                "correct_password = \"python123\"\n",
                "\n",
                "print(f\"您有{attempts}次机会输入正确密码\")\n",
                "\n",
                "for i in range(attempts):\n",
                "    password = input(f\"请输入密码（还剩{attempts - i}次机会）：\")\n",
                "\n",
                "    if password == correct_password:\n",
                "        print(\"密码正确，登录成功！\")\n",
                "        break  # 密码正确，跳出循环\n",
                "    else:\n",
                "        print(\"密码错误，请重试。\")\n",
                "else:  # 循环正常结束，说明用完了所有尝试机会但没有输入正确密码\n",
                "    print(\"尝试次数已用完，账户已锁定。请联系管理员解锁。\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## 3. 嵌套循环\n",
                "\n",
                "一个循环内部可以包含另一个循环，这称为嵌套循环："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 嵌套循环示例\n",
                "for i in range(1, 4):  # 外层循环\n",
                "    print(f\"外层循环：{i}\")\n",
                "    for j in range(1, 4):  # 内层循环\n",
                "        print(f\"  内层循环：{j}\")\n",
                "    print(\"---\")    "
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "**嵌套循环的应用场景:**\n",
                "1. 二维数据处理 - 处理表格、矩阵等数据\n",
                "2. 组合生成 - 生成所有可能的组合\n",
                "3. 图形绘制 - 绘制二维图形\n",
                "4. 复杂算法 - 实现需要多层迭代的算法"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 示例：打印星号图案（等腰三角形）\n",
                "height = 5  # 三角形的高度\n",
                "\n",
                "for i in range(height):\n",
                "    # 打印空格（左侧对齐）\n",
                "    for j in range(height - i - 1):\n",
                "        print(\" \", end=\"\")\n",
                "        \n",
                "\n",
                "    # 打印星号\n",
                "    for k in range(2 * i + 1):\n",
                "        print(\"*\", end=\"\")\n",
                "\n",
                "    print()  # 换行"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## 4. 实际应用案例"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 4.1 简易ATM机系统"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 简易ATM机系统\n",
                "# 这个例子综合了条件语句和循环结构的应用\n",
                "\n",
                "# 初始账户信息\n",
                "account_balance = 10000.0\n",
                "pin = \"1234\"\n",
                "transaction_history = []\n",
                "\n",
                "# 验证PIN码\n",
                "max_attempts = 3\n",
                "for attempt in range(max_attempts):\n",
                "    user_pin = input(\"请输入您的PIN码：\")\n",
                "\n",
                "    if user_pin == pin:\n",
                "        print(\"PIN码验证成功！\\n\")\n",
                "        break\n",
                "    else:\n",
                "        remaining = max_attempts - attempt - 1\n",
                "        if remaining > 0:\n",
                "            print(f\"PIN码错误，您还有{remaining}次尝试机会。\")\n",
                "        else:\n",
                "            print(\"PIN码错误次数过多，账户已锁定。\")\n",
                "else:  # PIN码验证失败\n",
                "    print(\"请联系银行客服解锁您的账户。\")\n",
                "    exit()  # 退出程序\n",
                "\n",
                "# 主菜单循环\n",
                "while True:\n",
                "    print(\"\\n===== ATM系统菜单 =====\")\n",
                "    print(\"1. 查询余额\")\n",
                "    print(\"2. 存款\")\n",
                "    print(\"3. 取款\")\n",
                "    print(\"4. 交易记录\")\n",
                "    print(\"5. 退出\")\n",
                "\n",
                "    choice = input(\"\\n请选择操作（1-5）：\")\n",
                "\n",
                "    if choice == \"1\":  # 查询余额\n",
                "        print(f\"\\n您的当前余额为：￥{account_balance:.2f}\")\n",
                "        transaction_history.append(f\"查询余额：￥{account_balance:.2f}\")\n",
                "\n",
                "    elif choice == \"2\":  # 存款\n",
                "        try:\n",
                "            amount = float(input(\"请输入存款金额：￥\"))\n",
                "            if amount <= 0:\n",
                "                print(\"存款金额必须大于零！\")\n",
                "                continue\n",
                "\n",
                "            account_balance += amount\n",
                "            transaction_history.append(f\"存款：￥{amount:.2f}\")\n",
                "            print(f\"存款成功！当前余额为：￥{account_balance:.2f}\")\n",
                "        except ValueError:\n",
                "            print(\"请输入有效的金额！\")\n",
                "\n",
                "    elif choice == \"3\":  # 取款\n",
                "        try:\n",
                "            amount = float(input(\"请输入取款金额：￥\"))\n",
                "            if amount <= 0:\n",
                "                print(\"取款金额必须大于零！\")\n",
                "                continue\n",
                "\n",
                "            if amount > account_balance:\n",
                "                print(\"余额不足！\")\n",
                "                continue\n",
                "\n",
                "            account_balance -= amount\n",
                "            transaction_history.append(f\"取款：￥{amount:.2f}\")\n",
                "            print(f\"取款成功！当前余额为：￥{account_balance:.2f}\")\n",
                "        except ValueError:\n",
                "            print(\"请输入有效的金额！\")\n",
                "\n",
                "    elif choice == \"4\":  # 交易记录\n",
                "        print(\"\\n===== 交易记录 =====\")\n",
                "        if transaction_history:\n",
                "            for i, transaction in enumerate(transaction_history, 1):\n",
                "                print(f\"{i}. {transaction}\")\n",
                "        else:\n",
                "            print(\"暂无交易记录。\")\n",
                "\n",
                "    elif choice == \"5\":  # 退出\n",
                "        print(\"感谢使用ATM系统，再见！\")\n",
                "        break\n",
                "\n",
                "    else:\n",
                "        print(\"无效的选择，请重新输入。\")\n",
                "\n",
                "    # 每次操作后询问是否继续\n",
                "    continue_choice = input(\"\\n按Enter键继续...\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "## 5. 流程控制的最佳实践"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 保持条件表达式简单清晰\n",
                "\n",
                "复杂的条件可以分解为多个变量或函数，使代码更易读："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 不易读的复杂条件\n",
                "age = 25\n",
                "income = 5000\n",
                "credit_score = 750\n",
                "\n",
                "if age >= 18 and age <= 65 and income >= 3000 and credit_score >= 700:\n",
                "    print(\"贷款申请已初步批准\")\n",
                "\n",
                "# 更易读的方式\n",
                "is_adult = age >= 18\n",
                "is_below_retirement = age <= 65\n",
                "has_sufficient_income = income >= 3000\n",
                "has_good_credit = credit_score >= 700\n",
                "\n",
                "if is_adult and is_below_retirement and has_sufficient_income and has_good_credit:\n",
                "    print(\"贷款申请已初步批准\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 避免嵌套过深\n",
                "\n",
                "过多的嵌套会使代码难以理解和维护。可以通过提前返回或跳过来减少嵌套："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 嵌套过深的代码\n",
                "def check_eligibility(age, income, credit_score):\n",
                "    if age >= 18:\n",
                "        if age <= 65:\n",
                "            if income >= 3000:\n",
                "                if credit_score >= 700:\n",
                "                    return \"贷款申请已初步批准\"\n",
                "                else:\n",
                "                    return \"信用分数不足\"\n",
                "            else:\n",
                "                return \"收入不足\"\n",
                "        else:\n",
                "            return \"超过年龄限制\"\n",
                "    else:\n",
                "        return \"未满18岁\"\n",
                "\n",
                "# 更清晰的方式：提前返回\n",
                "def check_eligibility_improved(age, income, credit_score):\n",
                "    # 提前检查所有不满足的条件\n",
                "    if age < 18:\n",
                "        return \"未满18岁\"\n",
                "    if age > 65:\n",
                "        return \"超过年龄限制\"\n",
                "    if income < 3000:\n",
                "        return \"收入不足\"\n",
                "    if credit_score < 700:\n",
                "        return \"信用分数不足\"\n",
                "\n",
                "    # 所有条件都满足\n",
                "    return \"贷款申请已初步批准\"\n",
                "\n",
                "# 测试两个函数\n",
                "print(check_eligibility(25, 5000, 750))\n",
                "print(check_eligibility_improved(25, 5000, 750))"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 使用适当的循环类型\n",
                "\n",
                "- 当你知道循环次数时，使用`for`循环\n",
                "- 当循环次数不确定，依赖于某个条件时，使用`while`循环"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 已知循环次数，适合使用for循环\n",
                "total = 0\n",
                "for i in range(1, 101):\n",
                "    total += i\n",
                "print(f\"1到100的和：{total}\")\n",
                "\n",
                "# 未知循环次数，适合使用while循环\n",
                "import random\n",
                "target = random.randint(1, 100)\n",
                "guesses = 0\n",
                "\n",
                "while True:  # 无限循环，直到猜对为止\n",
                "    guesses += 1\n",
                "    guess = random.randint(1, 100)  # 模拟猜测\n",
                "    if guess == target:\n",
                "        break  # 猜对了，跳出循环\n",
                "\n",
                "print(f\"模拟猜数字：猜了{guesses}次才猜对\")"
            ]
        },
        {
            "cell_type": "markdown",
            "metadata": {},
            "source": [
                "### 注意无限循环\n",
                "\n",
                "确保`while`循环的条件最终会变为`False`，或者在循环内部有`break`语句来退出循环："
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "metadata": {},
            "outputs": [],
            "source": [
                "# 确保循环会结束的几种方式\n",
                "\n",
                "# 1. 递减计数器\n",
                "count = 5\n",
                "while count > 0:\n",
                "    print(count)\n",
                "    count -= 1  # 确保count最终会变为0\n",
                "print(\"计数结束\")\n",
                "\n",
                "# 2. 用户控制退出\n",
                "while True:\n",
                "    response = input(\"\\n输入'quit'退出循环：\")\n",
                "    if response.lower() == 'quit':\n",
                "        break  # 用户输入'quit'时退出循环\n",
                "print(\"循环已退出\")\n",
                "\n",
                "# 注意：这里演示第二种方式时，如果您在Jupyter Notebook中运行，\n",
                "# 可能需要手动中断内核来停止执行，因为它会等待您的输入"
            ]
        }
    ],
    "metadata": {
        "kernelspec": {
            "display_name": "Python 3",
            "language": "python",
            "name": "python3"
        },
        "language_info": {
            "codemirror_mode": {
                "name": "ipython",
                "version": 3
            },
            "file_extension": ".py",
            "mimetype": "text/x-python",
            "name": "python",
            "nbconvert_exporter": "python",
            "pygments_lexer": "ipython3",
            "version": "3.11.12"
        }
    },
    "nbformat": 4,
    "nbformat_minor": 4
}
